﻿using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace RemoteSensingImageDirectServer.Register.Http
{
    public class CsvArrayDoubleModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var modelName = bindingContext.ModelName;
            var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);

            if (valueProviderResult == ValueProviderResult.None)
            {
                return Task.CompletedTask;
            }

            var value = valueProviderResult.FirstValue;
            if (value == "")
            {
                bindingContext.Result = ModelBindingResult.Success("");
            }

            var values = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            try
            {
                var doubleArray = values.Select(double.Parse).ToArray();
                bindingContext.Result = ModelBindingResult.Success(doubleArray);
            }
            catch (FormatException)
            {
                bindingContext.ModelState.AddModelError(modelName, "Invalid format for comma-separated integer array.");
            }

            return Task.CompletedTask;
        }
    }
}
